import 'package:happy_study/core/model/user_model.dart';
import 'package:happy_study/core/sqlite_database/util/db_provider.dart';
import 'package:sqflite/sqflite.dart';

class UserDao extends DBProvider {
  final String name = "user";
  final String columnId = "_id";

  @override
  tableName() {
    return name;
  }

  @override
  tableSqlString() {
    return tableBaseString(name, columnId) +
        '''
      userId text,
      userName text,
      userLevel integer,
      password text,
      userExperience integer)
    ''';
  }

  ///插入数据
  Future insert(user) async {
    Database db = await getDB();
    return await db.insert(name, UserModel.toMap(user));
  }

  Future<List<UserModel>> getAllUsers() async {
    List<UserModel> users = [];
    Database db = await getDB();
    List<Map<String, dynamic>> res = await db.query(name);
    if (res.isNotEmpty) {
      for (var json in res) {
        users.add(UserModel.fromJson(json));
      }
      return users;
    }
    return [];
  }

  Future<UserModel?> getUserByUserId(userId) async {
    Database db = await getDB();
    List<Map<String, dynamic>> res = await db.query(name, where: "userId = ?", whereArgs: [userId]);
    if (res.isNotEmpty) {
      return UserModel.fromJson(res.first);
    }
    return null;
  }
}
